package com.atguigu.async;

import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class FutureDemo01 {
    public static void main(String[] args) throws Exception {
        runAsync2();
        //supplyAsync();
    }

    //1.发起一个异步请求
    private static void runAsync() {
        CompletableFuture<Void> runFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                System.out.println("你好runAsync");
                int a=1/0;
            }
        }).whenComplete(new BiConsumer<Void, Throwable>() {
            //类似于vue里面的发起异步请求之后的then方法
            @Override
            public void accept(Void acceptVal, Throwable throwable) {
                System.out.println("获取上面执行完成之后的值:"+acceptVal);
                System.out.println("whenComplete接受到发生的异常"+throwable);
            }
        }).exceptionally(new Function<Throwable, Void>() {
            //类似于vue里面的发起异步请求之后的catch方法
            @Override
            public Void apply(Throwable throwable) {
                System.out.println("exceptionally接受到发生的异常"+throwable);
                return null;
            }
        });
    }
    //1.发起一个异步请求
    private static void runAsync2() {
        CompletableFuture<Void> runFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"你好runAsync");
                //int a=1/0;
            }
        }).whenCompleteAsync(new BiConsumer<Void, Throwable>() {
            //类似于vue里面的发起异步请求之后的then方法
            @Override
            public void accept(Void acceptVal, Throwable throwable) {
                System.out.println(Thread.currentThread().getName()+"获取上面执行完成之后的值:"+acceptVal);
                System.out.println("whenComplete接受到发生的异常"+throwable);
            }
        },MyExecutor.getInstance());
    }

    //2.发起一个异步请求
    private static void supplyAsync() throws Exception {
        CompletableFuture<Object> supplyFuture = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                System.out.println("你好supplyAsync");
                return 1024;
            }
        });
        System.out.println(supplyFuture.get());
    }
}
